package cn.yunbamboos.mybatis.metadata.where.item;

import cn.yunbamboos.mybatis.annotation.DateRange;
import cn.yunbamboos.mybatis.metadata.TableInfo;
import cn.yunbamboos.mybatis.metadata.where.TableWhere;
import org.apache.ibatis.scripting.xmltags.IfSqlNode;
import org.apache.ibatis.scripting.xmltags.MixedSqlNode;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.scripting.xmltags.StaticTextSqlNode;
import org.apache.ibatis.session.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class TableWhereDateRange extends TableWhere {

    private static final Logger logger = LoggerFactory.getLogger(TableWhereDateRange.class);

    private final TableInfo tableInfo;
    private final String column;

    private final String start;
    private final String end;

    public TableWhereDateRange(TableInfo tableInfo, Field field, DateRange dateRange) {
        this.tableInfo = tableInfo;
        this.column = dateRange.column();
        this.start = dateRange.start();
        this.end = dateRange.end();
    }

    @Override
    public Optional<SqlNode> createSqlNode(Configuration configuration) {
        List<SqlNode> contents = new ArrayList<>();
        createStartSqlNode(configuration).ifPresent(contents::add);
        createEndSqlNode(configuration).ifPresent(contents::add);
        return Optional.of(new MixedSqlNode(contents));
    }

    public Optional<SqlNode> createStartSqlNode(Configuration configuration) {
        String notNullTest = getNotNullTest(start);
        String notEmptyTest = getNotEmptyTest(start);

        StaticTextSqlNode sqlNode = new StaticTextSqlNode(" and " + column + " >= #{ " + CONDITIONS + DOT + start + " } ");
        return Optional.of(new IfSqlNode(sqlNode, notNullTest + SPACE + AND + SPACE + notEmptyTest));
    }

    public Optional<SqlNode> createEndSqlNode(Configuration configuration) {
        String notNullTest = getNotNullTest(end);
        String notEmptyTest = getNotEmptyTest(end);

        StaticTextSqlNode sqlNode = new StaticTextSqlNode(" and " + column + " <= #{ " + CONDITIONS + DOT + end + " } ");
        return Optional.of(new IfSqlNode(sqlNode, notNullTest + SPACE + AND + SPACE + notEmptyTest));
    }

}
